<template>
  <div>
    <h1>{{ id ? "编辑" : "新建" }}文章</h1>
    <el-form label-width="80px" :model="model" @submit.native.prevent="save">
      <el-form-item label="所属分类">
        <el-select v-model="model.categories" multiple placeholder="请选择">
          <el-option
            v-for="item in categories"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标题">
        <el-input v-model="model.title"></el-input>
      </el-form-item>
      <el-form-item label="详情">
        <vue-editor 
          v-model="model.body"
          useCustomImageHandler
          @image-added="handleImageAdded"
        ></vue-editor>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { VueEditor } from "vue2-editor";
export default {
  data() {
    return {
      // 指定id的数据
      model: {},
      categories: [],
      data: "<h1>jsdkf</h1>",
    };
  },
  components: {
    VueEditor,
  },
  props: {
    id: {},
  },
  methods: {
    // 保存
    async save() {
      // 如果要编辑分类
      if (this.id) {
        await this.$http.put(`/cdur/article/${this.id}`, this.model);
        // 如果要新建分类
      } else {
        await this.$http.post("/cdur/article", this.model);
      }
      this.$router.push("/article/list");
      this.$message.success("保存成功！");
    },
    // 获取指定id的文档
    async fetch() {
      const { data } = await this.$http.get(`/cdur/article/${this.id}`);
      this.model = data;
    },
    // 获取分类
    async fetchCategories() {
      const { data } = await this.$http.get(`/cdur/category`);
      this.categories = data;
    },
    // 自定义上传图片
    async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      const formData = new FormData();
      formData.append("file", file);
      const res = await this.$http.post("/upload", formData);
      Editor.insertEmbed(cursorLocation, "image", res.data.url);
      resetUploader();
    },
  },
  created() {
    this.fetchCategories();
    // 如果要编辑，则向后端发送请求获取数据
    this.id && this.fetch();
  },
};
</script>
